<?php
declare (strict_types = 1);

namespace app\shop_admin\controller;

use app\shop_admin\model\OrderCommodity;
use app\shop_admin\service\OrderService;
use app\utils\DaDaSdk;
use app\shop_admin\model\Dada as DD;
use app\shop_admin\model\Order;
use app\shop_admin\model\Distribution;

/**
 * 达达控制器
 * @package app\shop_admin\controller
 */
class DaDa extends BaseAction
{

    private function getSdK($oid)
    {
        $orderCommodity = (new Order())->orderCommodity()->where('order_id', $oid)->find();
        $distribution = Distribution::field('config')->where('store_id', $orderCommodity['store_id'])->find()->toArray();
        $config = json_decode($distribution['config'])[0];
        $appkey = $config->app_key;
        $appsec = $config->app_secret;
        $source_id = $config->app_source_id;
        $shop_no = $config->app_store_number;

        $dadasdk = new DaDaSdk($appkey,$appsec,$source_id,$shop_no);

        return $dadasdk;
    }

    /**
     * 达达回调地址
     * @return \think\response\Json
     */
    public function index()
    {
        $params = input('param.');
        DD::insertGetId([
            'cancel_reason' => serialize($params)
        ]);
        $res = [
            "status" => "success",
            "code" => 0,
            "msg" => "成功",
            "success" => true,
            "fail" => false
        ];
        return json($res, HTTP_SUCCESS);
    }

    /**
     * 达达付款配送
     * @param $oid int 订单id
     * @param $id int 达达订单
     */
    public function pay($oid, $id)
    {
        $dada = DD::find($id);
        $dadasdk = $this->getSdK($oid);
        $data['deliveryNo'] = $dada['client_id'];
        $res = $dadasdk->addAfterQuery($data);

        if ($res['status'] == "success") {
            DD::update([
                'id' => $id,
                'order_status' => 1
            ]);
            $msg = "1";
            // 订单发货
            $order = new OrderService();
            $order_data = [
                'id' => $oid,
                'type' => 1,
                'logistics_no' => $dada['client_id'],
                'express_company' => '达达快送',
                'status' => 3
            ];
            $order->saveOrderStatus($order_data);
            return json(['msg' => $msg], HTTP_SUCCESS);
        } else {
            $msg = $res['msg'];
            return json(['msg' => $msg], HTTP_NOTACCEPT);
        }
    }

    /**
     * 查询达达订单派送情况
     * @param $oid int 订单号
     * @return mixed
     */
    public function query($oid)
    {
        $order['order_id'] = Order::find($oid)['order_no'];
        $dadasdk = $this->getSdK($oid);
        $res = $dadasdk->query($order);
        return json(['msg' => $res], HTTP_SUCCESS);
    }

    /**
     * 订单取消
     * @param $oid int 订单id
     * @param $id int 取消订单id（达达平台获取）
     * @param string $reason 原因
     * @return \think\response\Json
     */
    public function formalCancel($oid, $id, $reason = "")
    {

        $order = Order::find($oid);
        $dadasdk = $this->getSdK($oid);

        $data['order_id'] = $order['order_no'];
        $data['cancel_reason_id'] = $id;
        $data['cancel_reason'] = $reason;
        $res = $dadasdk->formalCancel($data);
        // 取消订单发货
        $order = new OrderService();
        $ocs = OrderCommodity::where(['order_id' => $oid, 'status' => 3])->field('id as cid,sku_id')->select()->toArray();
        $order->cancelOrder(["order_id" => $oid], $ocs);
        // 取消达达订单
        DD::update(['order_status' => 5], ['order_id' => $oid]);
        return json(['msg' => $res], HTTP_SUCCESS);
    }

    /**
     * 查询达达城市code
     * @param $oid int 订单号
     * @return \think\response\Json
     */
    public function list($oid)
    {
        $dadasdk = $this->getSdK($oid);
        $res = $dadasdk->cityCode();
        return json(['msg' => $res], HTTP_SUCCESS);
    }

    /**
     * 订单取消原因
     * @param $oid int 订单号
     * @return \think\response\Json
     */
    public function reasons($oid)
    {
        $dadasdk = $this->getSdK($oid);
        $res = $dadasdk->cancelReasons();
        return json(['msg' => $res], HTTP_SUCCESS);
    }

}
